package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.templates.L1ItemHtml;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ItemHtmlTable {
  public static final Log _log = LogFactory.getLog(ItemHtmlTable.class);
  
  private static final HashMap<Integer, L1ItemHtml> _htmlMap = new HashMap<>();
  
  private static ItemHtmlTable _instance;
  
  public static ItemHtmlTable get() {
    if (_instance == null)
      _instance = new ItemHtmlTable(); 
    return _instance;
  }
  
  private ItemHtmlTable() {
    load();
  }
  
  public void load() {
    Connection cn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("SELECT * FROM `w_道具对话档`");
      rs = ps.executeQuery();
      while (rs.next()) {
        int itemid = rs.getInt("itemid");
        int quest_id = rs.getInt("quest_id");
        int quest_step = rs.getInt("quest_step");
        String html = rs.getString("html");
        if (ItemTable.get().getTemplate(itemid) == null) {
          _log.error("自定对话道具资料错误: 没有这个编号的道具:" + itemid);
          continue;
        } 
        L1ItemHtml value = new L1ItemHtml();
        value.setItemId(itemid);
        value.setQuestId(quest_id);
        value.setQuestStep(quest_step);
        value.setHtml(html);
        _htmlMap.put(Integer.valueOf(itemid), value);
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
    _log.info("载入自定对话道具:" + _htmlMap.size());
  }
  
  public L1ItemHtml getHtml(int itemid) {
    try {
      if (_htmlMap.containsKey(Integer.valueOf(itemid)))
        return _htmlMap.get(Integer.valueOf(itemid)); 
    } catch (Exception exception) {}
    return null;
  }
}
